<template>
  <div class='container'>
    <el-dialog :title="title" width="25%" :visible="$parent.showdialog" @close="handleClose">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="所属学科" prop='subjectID' v-if="!$route.query.id">
          <el-select v-model="form.subjectID" placeholder="请选择" style="width:80%">
            <el-option v-for="item in subList" :value="item.value" :key="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" style="width:80%"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '../../api/hmmm/tags'
import { simple } from '../../api/hmmm/subjects'

export default {

  data () {
    return {
      form: {
        id: 0,
        subjectID: null,
        tagName: ''
      },
      rules: {
        subjectID: [{ required: true, message: '不能为空', trigger: 'blur' }],
        tagName: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      subList: []
    }
  },
  async created () {
    this.subList = (await simple()).data
  },
  computed: {
    title () {
      return this.form.subjectID ? '修改标签' : '新增标签'
    }
  },
  methods: {
    handleClose () {
      this.$parent.showdialog = false
      this.$refs.form.resetFields()
      this.form = {
        id: 0,
        subjectID: null,
        tagName: ''
      }
    },
    async submit () {
      await this.$refs.form.validate()
      console.log(this.form.subjectID)
      this.form.id ? await update(this.form) : await add({ subjectID: this.form.subjectID ? this.form.subjectID : +this.$route.query.id, tagName: this.form.tagName })
      this.$message.success(`${this.form.id ? '修改' : '新增'}标签成功`)
      this.handleClose()
      this.$parent.getList()
    },
    async edit (id, tagName, subjectName) {
      this.form.id = id
      this.form.tagName = tagName
      this.form.subjectID = this.subList.find(ele => ele.label === subjectName).value
    }
  }
}
</script>

<style scoped lang='less'></style>
